import urllib, urllib2
from toscawidgets.core import Widget
try:
    #2.5 implementation
    import xml.etree.cElementTree as ET
except:
    #2.4 compat
    import cElementTree as ET

class YahooMapWidget(Widget):
    template = "genshi:toscawidgets.widgets.twtools.yahoo.templates.map"
    params = ["appID", "url"]

    url = "http://local.yahooapis.com/MapsService/V1/mapImage"
    appID="YourAppIdHere" 

    def update_params(self, d):
        self._my_update_params(d)
        Widget.update_params(self, d)
        return d

    def _my_update_params(self, d):
        value = d['value']
        d['url']=self._getImageUrl(value['lat'], 
                        value['long'], 
                        width=value['width'], 
                        height=value['height']-5,
                        zoom=value['zoom'])
        return d

    def _getImageUrl(self, lat, lng, width=620, height=500, image_type="gif", zoom=2):
        args = dict(appid=self.appID,
                    latitude=str(lat),
                    longitude=str(lng),
                    image_width=str(width),
                    image_height=str(height),
                    zoom=str(zoom))
        data =  urllib.urlencode(args)
        req =  urllib2.Request(self.url, data)
        handle =  urllib2.urlopen(req)
        dom = ET.parse(handle).getroot()
        return dom.text.encode('utf-8')
